import com.mit.web.business.proxy.PurchaseProxy;
import com.mit.web.business.remote.IInvokeResponder;
import com.mit.web.config.Constants;
import com.mit.web.event.PopWinCloseEvent;
import com.mit.web.util.LogUtil;
import com.mit.web.view.component.monitor.IProgressMonitor;
import com.mit.web.view.purchase.ColorStyleEditWindow;
import com.mit.web.view.purchase.MaterialEditWindow;
import com.mit.web.vo.purchase.ColorStyleVO;
import com.mit.web.vo.purchase.MaterialVO;

import flash.events.MouseEvent;

import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.controls.ToolTip;
import mx.core.INavigatorContent;
import mx.events.FlexEvent;
import mx.events.ListEvent;
import mx.events.MenuEvent;
import mx.events.TreeEvent;
import mx.logging.ILogger;
import mx.managers.ToolTipManager;
import mx.rpc.events.ResultEvent;
import mx.utils.StringUtil;

private var _itemList:ArrayCollection; //数据源, MaterialVO


private var _proxy:PurchaseProxy = PurchaseProxy.getInstance();
private var logger:ILogger;
private var _pm:IProgressMonitor;

[Bindable] private var _treesrc:ArrayCollection; //Tree data provider Object
[Bindable] private var _item:MaterialVO;
[Bindable] private var _color:ColorStyleVO;

[Bindable]
[Embed(source="../../assets/user.png")]
private var _supplierIcon:Class;
[Bindable]
[Embed(source="../../assets/item.png")]
private var _itemIcon:Class;
[Bindable]
[Embed(source="../../assets/colors.png")]
private var _colorIcon:Class;


private function init():void{			
	logger = LogUtil.getLogger(this);	
}



/**
 * 将数据源绑定到树形结构
 * {name:"代码", code:"名称",level:"1=root,2=原料,3=颜色",color="颜色值"
 * ,index="队列中的index", children:"子物件", enquired:"是否向数据库查询过子节点，如果是否，则会查询一次"}
 * 
 **/
private function bindToTree(src:ArrayCollection):void{
	_treesrc = new ArrayCollection();
	var products:ArrayCollection = new ArrayCollection();
	
	for(var i:int= 0;i<src.length;i++){
		var m:MaterialVO = MaterialVO(src[i]);
		var convertedColor:ArrayCollection  = new ArrayCollection();
		/* 可能物品太多，留到展开的时候才加载色卡
		if(m.colors.length > 0){						
			for(var j:int = 0; j<m.colors.length;j++){
				var c:ColorStyleVO = ColorStyleVO(m.colors[j]);
				var o:Object = {name:c.name, code:c.code, level:3, color:c.color,index:j, parentIndex:i};
				convertedColor.addItem(o);
			}
		}*/
		var convertedMaterial:Object =
			{name:m.name, code:m.code, level:2, index:i,children:convertedColor,enquried:false};
		
		products.addItem(convertedMaterial);
		
		
	}
	var root:Object =  {name:_supplier.selectedItem.label,level:1,children:products};
	_treesrc.addItem(root);
	
	//默认展开第一级
	_tree.validateNow();
	_tree.expandItem(root,true);
	
}

//根据tree的层级显示不同图标
private function iconFunc(item:Object):Class {
	var iconClass:Class;
	switch(item.level){
		case 1:
			iconClass = _supplierIcon;
			break;
		case 2:
			iconClass = _itemIcon;
			break;	
		case 3:
			iconClass = _colorIcon;
			break;
	}
	
	return iconClass;
}

/*
private function doView(event:MenuEvent):void{
	
	var onlyDisplayPurchased:Boolean = (event.index == 1);
	event.currentTarget.label = event.label;
	_currentSupplierId = _supplier.selectedItem.id;
	
	//TODO dummy code
	_itemList =  _proxy.getSupplierProducts(_currentSupplierId, onlyDisplayPurchased);
	
	bindToTree(_itemList);
	this.currentState = "view";
}
*/
private function doView(event:MouseEvent):void{
	var rsp:IInvokeResponder = _proxy.getSupplierProducts(_supplier.selectedId).installProgressBar(_pm, this);
	rsp.addFaultListener(exceptionHandler);
	rsp.addResultListener(loadProductHandler);
}

private function loadProductHandler(e:ResultEvent):void{
	_itemList = e.result as ArrayCollection;
	bindToTree(_itemList);
	this.currentState = "view";
}

//显示为编号+名称
private function treeFun(item:Object):String{
	if(item.code)
		return item.code + " " + item.name;
	else
		return item.name;
}



//选中item的事件，节点同时会展开
protected function _tree_itemClickHandler(event:ListEvent):void
{
	
	var o:Object = event.currentTarget.selectedItem;
	if(o.level == 2){
		//原料选中
		_item = _itemList[o.index];
		loadColors(o);
		this.currentState = "selectitem";
	}else if(o.level == 3){
		//颜色选中
		_item = _itemList[o.parentIndex];
		_color = _item.colors[o.index];
		this.currentState = "selectcolor";
	}else{
		this.currentState = "view";
	}
}

//展开item的事件:只点击了展开节点的图标，不是点击item
protected function _tree_itemOpenHandler(event:TreeEvent):void
{
	var o:Object = event.item;
	//只对第二层进行操作
	if(o.level == 2)
		loadColors(event.item);	
}

private function loadColors(treeItem:Object):void{
	//如果色卡没有加载，就查询数据库
	if(!treeItem.enquired){
		var product:MaterialVO = _itemList[treeItem.index];
		var rsp:IInvokeResponder = _proxy.getProductColors(product.id);
		rsp.addFaultListener(exceptionHandler);
		rsp.addResultListener(loadColorsHandler,treeItem);
	}	
	
	//展开本节点，关闭其他节点 
	//TODO，要考虑这样的行为对系统性能的影响
	var productItems:ArrayCollection = _treesrc[0].children;
	for(var i:int =0; i < productItems.length; i ++){
		if(i != treeItem.index)
			_tree.expandItem(productItems[i], false);
		else
			_tree.expandItem(productItems[i], true);
	}
}
//将色卡存入Product中
private function loadColorsHandler(event:ResultEvent, treeItem:Object):void{
	var colors:ArrayCollection = event.result as ArrayCollection;
	//存入数据源中
	var product:MaterialVO = _itemList[treeItem.index] as MaterialVO;
	product.colors = colors;
	
	//存入Tree resource中
	var convertedColor:ArrayCollection  = new ArrayCollection();
	if(colors){					
		for(var j:int = 0; j < colors.length;j++){
			var c:ColorStyleVO = ColorStyleVO(colors[j]);
			var o:Object = {name:c.name, code:c.code, level:3, color:c.color,index:j, parentIndex:treeItem.index};
			convertedColor.addItem(o);
		}
	}
	treeItem.enquired = true;
	treeItem.children = convertedColor;
	_tree.validateNow();	
	_tree.expandItem(treeItem,false);
	_tree.expandItem(treeItem,true);
}

//New Item
private function newItem(event:MouseEvent):void{
	_item = new MaterialVO();	
	_item.supplierId = _supplier.selectedId;
	_item.activeInd = Constants.YES;
	_item.type = Constants.PRIMARY;
	this.currentState = "selectitem";
}

//New Color
private function newColor(event:MouseEvent):void{
	//如果没有选中Item，给予提示
	if(_tree.selectedIndex < 1){
		
		var myError:String = "请先选择原料";
		showVerticalMiddleErrorTipAt(myError, _tree);
		
	}else{
		//如果选中的是原料，则根据index寻找原料，如果是选中颜色，根据parentIndex寻找原料
		if(_tree.selectedItem.level == 2)
			_item = _itemList[_tree.selectedItem.index];
		else
			_item = _itemList[_tree.selectedItem.parentIndex];
		_color = new ColorStyleVO();
		_color.materialId = _item.id;
		_color.activeInd = Constants.YES;
		this.currentState = "selectcolor";
	}
	
}

//Item edit window created 
private function itemEditWinCompleteHanlder(event:FlexEvent):void{
	var window:MaterialEditWindow = event.currentTarget as MaterialEditWindow;
	window.addEventListener(PopWinCloseEvent.CREATED, itemCreatedHandler);
	window.addEventListener(PopWinCloseEvent.SAVED, itemSavedHandler);
}

private function itemCreatedHandler(event:PopWinCloseEvent):void{
	var newItem:MaterialVO = event.vo as MaterialVO;
	_item = newItem;
	_itemList.addItem(newItem);
	
	//Update tree source
	//注意： children属性一定要给一个实例，否则继续 增加颜色的时候会出nullpointer
	//enquired set to true, no need ask DB for the newly created.
	var o:Object = {name:newItem.name, code:newItem.code
		, children:new ArrayCollection(), level:2, index:_itemList.length - 1,enquried:true};
	_treesrc[0].children.addItem(o);
	
	//refresh tree
	_tree.validateNow();
	_tree.selectedItem = o;
	
	showMessageTip(event.msg, _tree);
}

private function itemSavedHandler(event:PopWinCloseEvent):void{
	var savedItem:MaterialVO = event.vo as MaterialVO;
	_item = savedItem;
	var root:Object = _treesrc[0];
	var item:Object = root.children[_tree.selectedItem.index];
	item.name = _item.name;
	item.code = _item.code;
	
	showMessageTip(event.msg, _tree);
	_tree.validateNow();
	_tree.expandItem(root,false);
	_tree.expandItem(root,true);
}

//为颜色编辑增加监听器
private function colorEditWinCompleteHanlder(event:FlexEvent):void{
	var window:ColorStyleEditWindow = event.currentTarget as ColorStyleEditWindow;
	window.addEventListener(PopWinCloseEvent.CREATED, colorCreatedHandler);
	window.addEventListener(PopWinCloseEvent.SAVED, colorSavedHandler);
}

private function colorCreatedHandler(event:PopWinCloseEvent):void{
	var savedColor:ColorStyleVO = event.vo as ColorStyleVO;
	_color = savedColor;
	//Add to list;
	_item.addColor(_color);
	
	//Update tree source
	//取得父类的index
	var pIndex:int = _itemList.getItemIndex(_item);
	var o:Object = {name:_color.name, code:_color.code, level:3, index:_item.colors.length - 1, parentIndex:pIndex};
	var i:Object = _treesrc[0].children[pIndex];
	i.children.addItem(o);
	
	//refresh tree
	_tree.validateNow();
	_tree.expandItem(i,true);
	_tree.selectedItem = o;
	
	showMessageTip(event.msg, _tree);
}

private function colorSavedHandler(event:PopWinCloseEvent):void{
	var savedColor:ColorStyleVO = event.vo as ColorStyleVO;
	_color = savedColor;
	//Refresh tree
	var root:Object = _treesrc[0];
	var item:Object = root.children[_tree.selectedItem.parentIndex];
	var color:Object = item.children[_tree.selectedItem.index];
	color.name = _color.name;
	color.code = _color.code;
	
	_tree.validateNow();
	_tree.expandItem(item,false);
	_tree.expandItem(item,true);
	
	showMessageTip(event.msg, _tree);
}



